package controller

import (
	"gin_web/databases"
	"gin_web/model"
	"gin_web/query"
	"gin_web/utils"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
	"net/http"
)

type UserController struct {
	DB *gorm.DB
}

// NewUserController 新建实例
func NewUserController() *UserController {
	db := databases.DB
	db.AutoMigrate(&model.User{})
	return &UserController{DB: db}
}

// Save 添加一条数据
func (u UserController) Save(ctx *gin.Context) {
	user := model.User{
		UserId: uuid.NewV4(),
	}
	err := ctx.ShouldBind(&user)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{})
		utils.ErrorR(ctx, "参数有误")
	}
	u.DB.Create(&user)
	utils.SuccessR(ctx, nil, "保存成功")
}

// Update 更新
func (u UserController) Update(ctx *gin.Context) {
	var user model.User
	err := ctx.ShouldBind(&user)
	if err != nil {
		utils.ErrorR(ctx, "参数有误")
		return
	}
	u.DB.Save(&user)
	utils.SuccessR(ctx, nil, "更新成功")
}

// Get 按id获取
func (u UserController) Get(ctx *gin.Context) {
	var user query.UserQuery
	err := ctx.ShouldBind(&user)
	if err != nil {
		utils.ErrorR(ctx, "参数有误")
		return
	}
	u.DB.Where("user_name = ?", user.UserName).Find(&user)
	utils.SuccessR(ctx, user, "")
}

// Delete 按id删除
func (u UserController) Delete(ctx *gin.Context) {
	userId := ctx.PostForm("user_id")
	tx := u.DB.Where("user_id = ?", userId).Delete(&model.User{})
	if tx.Error != nil {
		utils.ErrorR(ctx, "")
		return
	}
	utils.SuccessR(ctx, nil, "")
}

// PageList 分页
func (u UserController) PageList(ctx *gin.Context) {
	var users []model.User
	total := PageList(ctx, u.DB, &users)
	utils.SuccessR(ctx, gin.H{
		"total": total,
		"rows":  users,
	}, "")
}
